//
//  UseSet.m
//  BSS
//
//  Created by Juvi on 13-5-30.
//  Copyright (c) 2013年 juvid. All rights reserved.
//

#import "UseSet.h"
#import "ChangCity.h"
#import "AboutOur.h"
#import "Common.h"
#import "FeedbackOnLine.h"
#import "DetectionSystemVersion.h"
#import "UseSetCell.h"
#import "SBJson.h"
#import "UIColor+expanded.h"

@interface UseSet ()

@end

@implementation UseSet

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[DetectionSystemVersion alloc]Version]) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
    
    [self BackButton];
    [self setVieWeb];
    self.table.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.table.backgroundColor=[UIColor colorWithHexString:@"0xe4e4e4"];
    
    // Do any additional setup after loading the view from its nib.
}
-(void)GetVersion{
    [self ShowHUD];
    tRequest=[[[ScreenAccess alloc]init]ASINewVersion];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"Version"];
}
-(void)ShowHUD{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.delegate = self;
    HUD.labelText = @"正在搜索最新版本...";
    [self.view addSubview:HUD];
    [HUD show:YES];
}
-(void)setVieWeb{
    [self.vieTable.layer setCornerRadius:5.0];
    self.aboutUsView.frame = self.navigationController.view.frame;
    NSString *strContent=@"“百事搜”是号百信息服务有限公司推出的一款基于自然语言搜索的智能语音搜索类客户端软件,可以帮助用户快速准确查找各类出行、休闲娱乐、理财等信息，覆盖商家查询、列车时刻、航班信息、天气预报、星座运势、笑话祝福、猜猜谜语、歌词查询、影视剧情、电影演出、美食菜谱、股票动态、彩票中奖、汇率利率、百科知识等多个领域。";
    NSString *webviewText = @"<style>body{margin:0;background-color:transparent;color:3a3a3a;font:16px/25px Custom-Font-Name}</style>";
    webviewText = [webviewText stringByAppendingFormat:@"%@",strContent];
    self.webView.backgroundColor=[UIColor clearColor];
    [_webView setOpaque:NO];
    [(UIScrollView *)[[_webView subviews] objectAtIndex:0] setBounces:NO];
    [self.webView loadHTMLString:webviewText baseURL:nil]; //在 WebView 中显示本地的字符串
}
-(void)requestFinished:(ASIHTTPRequest*)request{
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    if ([request.username isEqual:@"Version"]) {
        HUD.hidden=YES;
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *nowVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
        NSArray *infoArray = [Result objectForKey:@"results"];
        if ([infoArray count]) {
            NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
            lastVersion = [releaseInfo objectForKey:@"version"];
            if (![lastVersion isEqualToString:nowVersion]) {
                upDataMessage=[[infoArray objectAtIndex:0]objectForKey:@"releaseNotes" ];
                trackViewURL=[NSString stringWithFormat:@"%@",[releaseInfo objectForKey:@"trackViewUrl"]];
                [self UpdateVersion];
                
            }
            else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"你当前已是最新版本" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                
//                NSTimer *myTimer = [NSTimer  timerWithTimeInterval:10.0 target:self selector:@selector(UpdateVersion) userInfo:nil repeats:NO];
//                [[NSRunLoop  currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
            }
        }
    }
}


-(void)requestFailed:(ASIHTTPRequest*)request{
    HUD.labelText=@"请检查网络连接!";
    HUD.customView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"HUDProblem"]];
    HUD.mode = MBProgressHUDModeCustomView;
    [HUD hide:YES afterDelay:1.0]; 
}
#pragma mark MBProgressHUDDelegate methods


- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    HUD = nil;
}
#pragma mark 版本更新
-(void)UpdateVersion{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"发现新版本 %@",lastVersion] message:upDataMessage delegate:self cancelButtonTitle:@"暂不更新" otherButtonTitles:@"立即更新", nil];
    //    NSLog(@"%@",trackViewURL);
    [alert show];
}
#pragma mark 弹框代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
    if ([buttonTitle isEqualToString:@"立即更新"]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:trackViewURL]];
        
    }
}

-(void)BackButton{
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
-(void)viewDidAppear:(BOOL)animated{
     arrSet=[[NSArray alloc]initWithObjects:@"消息推送",@"当前城市",@"语音识别引擎",@"版本及更新",@"意见反馈",@"关于我们", nil];
    mlArrRight=[[NSMutableArray alloc]initWithObjects:[Common GetCity],@"讯飞",@"v1.0", nil];
    [self.table reloadData];

}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    //    [self.navigationController.view removeFromSuperview];
    [self HidePick:self.navigationController.view];
    [self.navigationController removeFromParentViewController];
}
#pragma mark 动画
-(void)HidePick:(UIView *)vieBounced {
    [UIView animateWithDuration:0.3
                     animations:^(void) {
                         vieBounced.alpha = 0.0;
                         //                         vieBounced.frame = CGRectMake(0, self.view.frame.size.height, 104, (self.view.frame.size.height-117-8)/3);
                     } completion:^(BOOL finished) {
                         
                         [vieBounced removeFromSuperview];
                     }];
    
}

-(void)ShowPick:(UIView *)vieBounced{
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^(void){
                         vieBounced.alpha = 1.0;
                     }
     
                     completion:^(BOOL finished) {
                     }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return arrSet.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"UseSetCell";
    UseSetCell *cell=(UseSetCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        cell=[[[NSBundle mainBundle]loadNibNamed:CellIdentifier owner:self options:Nil]objectAtIndex:0];
         cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.font=[UIFont systemFontOfSize:15];
    cell.textLabel.text=[arrSet objectAtIndex:indexPath.row];
    cell.textLabel.backgroundColor=[UIColor clearColor];
    if (indexPath.row==0) {
         cell.accessoryType=UITableViewCellAccessoryNone;
        UIButton *btnSwi=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 49, 40)];
        [btnSwi setImage:[UIImage imageNamed:[Common GetNotification]] forState:UIControlStateNormal];
        [btnSwi setTitle:[Common GetNotification] forState:UIControlStateNormal];
        [btnSwi addTarget:self action:@selector(PressSwich:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView=btnSwi;
        
    }
    if (indexPath.row==1||indexPath.row==2||indexPath.row==3) {
        if (indexPath.row==2) {
             cell.accessoryType=UITableViewCellAccessoryNone;
        }
//        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(160, 0, 130, 44)];
//        lab.textAlignment=NSTextAlignmentRight;
        cell.labCity.text=[mlArrRight objectAtIndex:indexPath.row-1];
//        lab.text=[mlArrRight objectAtIndex:indexPath.row-1];
//        lab.font=[UIFont systemFontOfSize:15];
//        [cell.contentView addSubview:lab];
    }
    UIView *vie=[[UIView alloc]init];
     vie.backgroundColor=[UIColor colorWithHexString:@"0xf3f3f3"];
    cell.backgroundView=vie;
    
//    cell.textLabel.textColor=[UIColor whiteColor];
       return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    FeedbackOnLine *feedbackOnLine=[[FeedbackOnLine alloc]init];
    ChangCity *changCity=[[ChangCity alloc]init];
    switch (indexPath.row) {
        case 1:
            changCity.strCurrentCiy=[mlArrRight objectAtIndex:indexPath.row-1];
            [self.navigationController pushViewController:changCity animated:YES];
            break;
        case 3:
            [self GetVersion];
            break;
        case 4:
            [self.navigationController pushViewController:feedbackOnLine animated:YES];
            break;
        case 5:{
           
            [self.navigationController.view addSubview:self.aboutUsView];
            //self.vieTable.frame=CGRectMake(0, 0, self.vieTable.frame.size.width, 46+44*arrRight.count);
            
            [self ShowPick:self.aboutUsView ];
        }
            break;
  
        default:
            break;
    }
}

-(void)PressSwich:(UIButton *)buto{
    if ([buto.currentTitle isEqual:@"btnSwichOff"]) {
        [Common SetNotification:@"btnSwichOn"];
        [buto setImage:[UIImage imageNamed:@"btnSwichOn"] forState:UIControlStateNormal];
        [buto setTitle:@"btnSwichOn" forState:UIControlStateNormal];

    }
    else{
         [Common SetNotification:@"btnSwichOff"];
       [buto setImage:[UIImage imageNamed:@"btnSwichOff"] forState:UIControlStateNormal];
         [buto setTitle:@"btnSwichOff" forState:UIControlStateNormal];
    }
   

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)HideVie:(id)sender {
    [self HidePick:self.aboutUsView];
}
@end
